package com.example.myapplication.ui.viewmodel

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.example.myapplication.ui.FileBean
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger

abstract class FileViewModel<T : FileBean> : ViewModel(), DefaultLifecycleObserver {

    companion object {
        val DB = Executors.newSingleThreadExecutor()
    }

    protected val NET: ThreadPoolExecutor

    init {
        NET = ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, LinkedBlockingQueue())
    }

    abstract fun insert(t: T)

    abstract fun retry(t: T)

    abstract fun delete(t: T)

    abstract fun deleteAllFinish()

    abstract fun listData(): LiveData<List<T>>

    abstract fun initData()

    abstract fun findReadyTask(): T?

    abstract fun clearAllRunning()

    abstract fun clearAllFailure()

    abstract fun updateAllFailure()

    private val taskSize = AtomicInteger(0)

    protected fun addTask(run: () -> Unit) {
        // 判断任务是否已满
        val addAndGet = taskSize.get()
        if (addAndGet >= 2) {
            return
        }
        // 任务标志+1
        taskSize.getAndIncrement()
        run.invoke()
    }

    protected fun currTask(): Int {
        return taskSize.get()
    }

    protected fun removeTask() {
        taskSize.getAndDecrement()
        if (taskSize.get() < 0) {
            taskSize.set(0)
        }
    }

}